package com.primemobi.oauth2.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.opensymphony.xwork.ActionSupport;

public class OAuthAction extends ActionSupport {
	private String oauthUrl;
	private String error;
	private String code;
	String grant_type = "authorization_code";
	
	// google api console 参数
	String client_id = "659041774760.apps.googleusercontent.com";
	String client_secret = "pDySy8x3qrr-MLLvXD8wfFea";
	String redirect_uri = "http://www.acsedu.hk/tqb_news/oauth2callback.action";
	
	
	public String test() throws Exception {
		return SUCCESS;
	}
	
	public String oauth() throws Exception {
		// 发送权限获取请求
		oauthUrl = "https://accounts.google.com/o/oauth2/auth?response_type=code&client_id="+client_id+"&redirect_uri="+redirect_uri+"&scope=https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile";
		return SUCCESS;
	}

	/**
	 * 参考文档https://developers.google.com/accounts/docs/OAuth2WebServer
	 * 
	 * An error response:  https://oauth2-login-demo.appspot.com/code?error=access_denied&state=/profile
	 * An authorization code response:  https://oauth2-login-demo.appspot.com/code?state=/profile&code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7
	 * 
	 * After the web server receives the authorization code, it may exchange the
	 * authorization code for an access token and a refresh token. This request
	 * is an HTTPs post, and includes the following parameters:
	 * 
	 * code: The authorization code returned from the initial request
	 * client_id The client_id obtained during application registration
	 * client_secret The client secret obtained during application registration
	 * redirect_uri The URI registered with the application
	 * grant_type As defined in the OAuth 2.0 specification, this field must contain a value of authorization_code The actual request might look like:
	 * 
	 * POST /o/oauth2/token HTTP/1.1 Host: accounts.google.com Content-Type:
	 * application/x-www-form-urlencoded
	 * 
	 * code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
	 * client_id=8819981768.apps.googleusercontent.com&
	 * client_secret={client_secret}&
	 * redirect_uri=https://oauth2-login-demo.appspot.com/code&
	 * grant_type=authorization_code
	 * 
	 * A successful response is returned as a JSON array, similar to the following:
	 * {
	 *   "access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
	 *   "expires_in":3920,
	 *   "token_type":"Bearer"
	 * }
	 * 
	 * @return
	 * @throws Exception
	 */
	public String oauth2callback() throws Exception {
		if(error!=null && error.equals("access_denied")){
			return INPUT;
		}
		String url = "https://accounts.google.com/o/oauth2/token";
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
		List <NameValuePair> nvps = new ArrayList <NameValuePair>();
		nvps.add(new BasicNameValuePair("code", code));
		nvps.add(new BasicNameValuePair("client_id", client_id));
		nvps.add(new BasicNameValuePair("client_secret", client_secret));
		nvps.add(new BasicNameValuePair("redirect_uri", redirect_uri));
		nvps.add(new BasicNameValuePair("grant_type", grant_type));
		httpPost.setEntity(new UrlEncodedFormEntity(nvps));
		
		HttpResponse response1;
		try {
			response1 = httpclient.execute(httpPost);
		} catch (ClientProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return INPUT;
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return INPUT;
		}

		// The underlying HTTP connection is still held by the response object
		// to allow the response content to be streamed directly from the
		// network socket.
		// In order to ensure correct deallocation of system resources
		// the user MUST either fully consume the response content or abort
		// request
		// execution by calling HttpGet#releaseConnection().

		try {
			System.out.println(response1.getStatusLine());
			HttpEntity entity1 = response1.getEntity();
			// do something useful with the response body
			// and ensure it is fully consumed
			try {
				EntityUtils.consume(entity1);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} finally {
			httpPost.releaseConnection();
		}
		return SUCCESS;
	}

	public String getOauthUrl() {
		return oauthUrl;
	}

	public void setOauthUrl(String oauthUrl) {
		this.oauthUrl = oauthUrl;
	}

	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}
	
}
